package com.android.wellcherish.kotlindemo2

import android.view.View
import org.json.JSONObject
import java.nio.charset.Charset
import kotlin.math.exp

/**
 * @author 张文琛
 * @date 2020/8/2 21:03
 *
 * 密封类不能被实例化，且子类必须定义在同一个文件中
 */
sealed class ChatMsg(var msgId: String = "", var msgType: MsgType = MsgType.UNKNOWN) {
    lateinit var data: ByteArray

}

class Text(msgId: String, msgType: MsgType): ChatMsg(msgId, msgType) {
    lateinit var content: String

    fun setContentByArray(array: ByteArray) {
        this.content = String(array)
    }
}

class Voice(msgId: String, msgType: MsgType): ChatMsg(msgId, msgType) {
    private var length: Int = 0
    private var voiceData: ByteArray? = null

    fun setDataByArray(array: ByteArray) {
        var content = String(array)
        // String 转 JSON 结构体
        var data = Data()
        val obj = JSONObject(content)
        val it = obj.keys()

        // 遍历 JSONObject
        while (it.hasNext()) {
            var key = it.next().toString()
            if(key == "length") {
                data.length = obj.getInt(key)
            } else if(key == "data") {
                data.data = obj.getString(key).toByteArray()
            }
        }

        this.length = data.length
        when (data.data) {
            null -> {
                this.voiceData = ByteArray(3) {0}
            }
            else -> {
                this.voiceData = data.data
            }
        }
    }

    class Data(var length: Int = 0, var data: ByteArray = "null".toByteArray()) {
        override fun toString(): String {
            return "{" + "\"length\":" + length + "\"data\":" + String(data) + "}"
        }
    }
}